﻿using System;
using System.Linq;
using ACompany.OrderProcessing.Model;
using ACompany.OrderProcessing.Services;

namespace ACompany.OrderProcessing.Presentation.Customer
{
    public class CustomerListPresenter
    {
        private readonly ICustomerListView _view;
        private readonly ICustomerService _customerService;

        #region ctors
        public CustomerListPresenter(ICustomerListView view)
            : this(view, new CustomerService())
        {

        }

        public CustomerListPresenter(ICustomerListView view, ICustomerService customerService)
        {
            _customerService = customerService;
            _view = view;
        }
        #endregion


        #region methods
        public void Display()
        {
            ClearInfoAndErrorMessages();
            _view.Customers = _customerService.FindAll().ToList();
            _view.ViewTitle("Customer List");
        }

        public void RemoveCustomerBy(Guid customerId)
        {
            ClearInfoAndErrorMessages();
            Model.Customer customer = _customerService.FindBy(customerId);

            if (customer != null)
            {
                if (customer.Orders.Count == 0)
                {
                    _customerService.Remove(customer);
                    Display();
                }
                else
                {
                    _view.ErrorMessage("cannot delete a customer that has orders");
                }
            }
            else
            {
                _view.ErrorMessage(string.Format("there is no customer with id:{0}", customerId));
            }
        }

        private void ClearInfoAndErrorMessages()
        {
            _view.InfoMessage(string.Empty);
            _view.ErrorMessage(string.Empty);
        } 
        #endregion


    }
}
